<template>
  <div id="Course">
    <div class="mt-4">
      <el-input
        v-model="queryValue"
        placeholder="请输入查询值"
        class="input-with-select"
        style="float: left;width: 300px"
        @keydown.enter.native="selectCourse(queryValue)"
      >
        <template #prepend>课程名:</template>
        <template #append>
          <el-button :icon="Search" @click="selectCourse(queryValue)" />
        </template>
      </el-input>
      <el-button plain type="primary" circle style="margin-left: 20px" @click="clickAllCourse" >All</el-button>
      <el-button plain :icon="Plus" :round="true" style="float: right" @click="clickToAdd">添加课程</el-button>
      <el-table :data="courseAllData" empty-text="未查询到数据！" table-layout="auto" >
        <el-table-column fixed prop="cname" label="课程名" />
        <el-table-column prop="cnum" label="课程需求人数" />
        <el-table-column label="操作" header-align="center" width="210">
          <template #default="scope">
            <el-button plain type="primary" :icon="Edit" @click="clickToModify(scope.row)">修改</el-button>
            <el-divider direction="vertical" />
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon-color="#626AEF"
              title="你确定要删除吗？"
              @confirm="clickToDelete(scope.row)"
            >
              <template #reference>
                <el-button type="danger" plain :icon="Delete">删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        hide-on-single-page
        :page-sizes="[10]"
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        @current-change="pageChange"
      />
    </div>
    <el-dialog
      v-model="courseDialogVisible"
      :title="courseTitle"
      width="30%"
      :before-close="closeForm"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseRules"
        label-width="100px"
        style="overflow: hidden;padding-right: 50px;width: 60%;margin: 10px auto"
      >
        <el-form-item label="课程名" prop="cname">
          <el-input v-model="courseForm.cname" :disabled="courseTitle === '修改课程'" />
        </el-form-item>
        <el-form-item label="需求人数" prop="cnum">
          <el-input v-model="courseForm.cnum" />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button-group>
            <el-button type="success" @click="submitForm(courseFormRef)">确认</el-button>
            <el-button type="info" @click="closeForm">取消</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {ref, unref} from "vue";
import {Search,Plus,Edit,Delete} from "@element-plus/icons-vue"
import axios from "axios";
import {ElNotification} from "element-plus";

export default {
  name: "CourseSys",
  setup() {

    /*查询*/
    let queryValue = ref()
    let queryItem = ref()
    let selectMode = ref(1) //1:全部，2：查询
    const selectCourse = (queryValue) => {
      if (queryValue == null) {
        clickAllCourse()
      } else {
        console.log(queryValue)
        getCourseAll("/api/getCourseByName?pageNum=1&pageSize=10&queryValue="+queryValue)
        selectMode.value = 2
        currentPage.value = 1
      }
    }
    const clickAllCourse = () => {
      selectMode.value = 1
      currentPage.value = 1
      getCourseAll("/api/getCourseAllData?pageNum=1&pageSize=10")
      queryValue.value = ""
    }

    /*添加 and 修改 and 删除*/
    let courseDialogVisible = ref(false)
    const clickToModify = (data) => {
      courseDialogVisible.value = true
      courseTitle.value = "修改课程信息"
      courseForm.value = JSON.parse(JSON.stringify(data))
    }
    const clickToDelete = (data) => {
      axios.post("/api/deleteCourse", data, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then(res=>{
        if (res.data.code === 200) {
          ElNotification({
            title: '成功',
            message: res.data.msg,
            type: 'success',
            offset: 100,
          })
        } else {
          ElNotification({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            offset: 100,
          })
        }
        clickAllCourse()
      })
    }
    const clickToAdd = () => {
      courseDialogVisible.value = true
      courseTitle.value = "添加课程"
    }

    /*表格*/
    let courseAllData = ref()

    /*分页*/
    let total = ref(0)
    let currentPage = ref(1)
    const pageChange = (val) => {
      currentPage.value = val
      if (selectMode.value === 1) {
        getCourseAll("/api/getCourseAllData?pageNum="+val+"&pageSize=10")
      } else if (selectMode.value === 2) {
        getCourseAll("/api/getCourseByName?pageNum="+val+"&pageSize=10&queryValue="+queryValue)
      }
    }

    /*弹出表单*/
    let courseTitle = ref("添加课程")
    let courseFormRef = ref()
    let courseForm = ref({
      cname: "",
      cnum: 0,
    })



    let courseRules = ref()
    const submitForm = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          if (courseTitle.value === "添加课程") {
            axios.post("/api/addCourse", JSON.parse(JSON.stringify(courseForm.value)), {
              headers:{
                token: localStorage.getItem("token")
              }
            }).then(res => {
              console.log('res =>'+courseForm.value.cname)
              if (res.data.code === 200) {
                ElNotification({
                  title: '成功',
                  message: res.data.msg,
                  type: 'success',
                  offset: 100,
                })
                courseDialogVisible.value = false

              } else {
                ElNotification({
                  title: '错误',
                  message: res.data.msg,
                  type: 'error',
                  offset: 100,
                })
              }
              clickAllCourse()
            })
          } else if (courseTitle.value === "修改课程信息") {
            axios.post("/api/updateCourse", JSON.parse(JSON.stringify(courseForm.value)), {
              headers:{
                token:localStorage.getItem("token")
              }
            }).then(res => {
              if (res.data.code === 200) {
                ElNotification({
                  title: '成功',
                  message: res.data.msg,
                  type: 'success',
                  offset: 100,
                })
                courseDialogVisible.value = false

              } else {
                ElNotification({
                  title: '错误',
                  message: res.data.msg,
                  type: 'error',
                  offset: 100,
                })
              }
              clickAllCourse()
            })
          }
        }
        unref(courseFormRef).resetFields()
      })
    }
    const closeForm = () => {
      courseForm.value = {
        cname: "",
        cnum: 0
      }
      unref(courseFormRef).resetFields()
      courseDialogVisible.value = false
    }

    /*数据*/
    getCourseAll("/api/getCourseAllData?pageNum=1&pageSize=10")
    function getCourseAll(url) {
      axios.get(url, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then(res => {
        if (res.data.code === 200) {
          courseAllData.value = res.data.data.courseList
          total.value = res.data.data.total
        } else {
          ElNotification({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            offset: 100,
          })
          courseAllData.value = []
          total.value = 0
        }
      })
    }

    courseRules.value = {
      cname: [
        { required: true, trigger: 'blur', validator: checkCname },
      ],
      cnum: [
        { required: true, trigger: 'blur', validator: checkCnum },
      ]
    }

    function checkCname(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入课程名！！'));
      } else {
        callback()
      }
    }
    function checkCnum(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入课程人数！！'));
      } else if (value <= 0) {
        return callback(new Error("课程所需人数不能小于0"))
      }else {
        callback()
      }
    }

    return {
      /*查询*/
      queryValue,
      queryItem,
      clickAllCourse,
      selectCourse,
      /*添加 and 修改*/
      courseDialogVisible,
      clickToModify,
      clickToDelete,
      clickToAdd,
      /*表格*/
      courseAllData,
      /*分页*/
      total,
      currentPage,
      pageChange,
      /*弹出表单*/
      courseTitle,
      courseFormRef,
      courseForm,
      courseRules,
      submitForm,
      closeForm,
      /*图标*/
      Search,
      Plus,
      Edit,
      Delete
    }
  }
}
</script>

<style scoped>
#Course {
  margin: 50px auto;
  width: 50%;
  min-width: 1000px;
}
.el-pagination {
  float: right;
  margin: 50px auto;
}
</style>